
#include <stdio.h>
#include "itcpserver.h"
#include "tools.h"

int Clients[5000] = {0};
int count = 0;
class ServerNetworkDelegate : public NetworkDelegate
{
public:
	virtual int CloseConnectCallBack(ItcpThreadOwner *owner, int connectIdx)
	{
		RETURN( errcode::enFunctionReturnValue_Sucess);
	}
	virtual int OpenConnectCallBack(ItcpThreadOwner *owner, int connectIdx)
	{
		Clients[count++] = connectIdx;
		RETURN( errcode::enFunctionReturnValue_Sucess);
	}
};

int main(int argc, char *argv[])
{


	if(argc < 3)
	{
		OutPutDebugStringToCMD("not enough param: Server --port --maxclientcount\n");
	}

	ITCPServer* Server = CreateTCPServer();
	if ( !Server )
		return 1;

	Server->StartServer( atoi(argv[1]),atoi(argv[2]));
	ServerNetworkDelegate networkdelegate;
	Server->SetNetworkDelegate(&networkdelegate);
	TimerStart();
	

	//char md5[1024] = {0};
	//char* filename="d:\\aa.txt";
	//file_md5( filename, md5 );

	//OutPutDebugStringToCMD("filemd5:%s\n", md5);

	//char* stringtest ="md5test";
	//string_md5( stringtest, md5 );

	//OutPutDebugStringToCMD("stringMd5:%s\n", md5);

	//


	unsigned int dataSize = 0;
	char recvRet[2048] = {0};
	while (true)
	{
		for (int i = 0; i < count; i++)
		{
			do 
			{
				void *header = Server->Peek(Clients[i], sizeof(TCPNetPack));
				if (header == NULL)
				{
					break;
				}

				TCPNetPack *PackHeader = (TCPNetPack*)header;
				if (PackHeader->buffsize <= 0)
				{
					return 1;
				}
				Server->GetDataFromRecvBuffByLength(Clients[i], recvRet, sizeof(TCPNetPack)+PackHeader->buffsize-1);
				if (recvRet == NULL)
				{
					break;
				}

				TCPNetPack *Packet = (TCPNetPack*)recvRet;

				OutPutDebugStringToCMD("Recv:%d %s",Packet->buffsize, Packet->buff);
				char temp[100] = {0};
				sprintf(temp,"nimei!%d\n", i);

				Server->PushDataToSendBuff(Clients[i], temp, strlen(temp));
				continue;

			} while (1);
		}


		Sleep(1);
		
	}

	getchar();

	Server->StopServer();
	return 0;
}
